#include "trimatrix.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>

Trimatrix* trimatrix_alloc(int n)
{
  assert(n >= 0);  

  int elem_size = n * (n+1) / 2 * sizeof(int);
  Trimatrix* matrix = malloc(sizeof(Trimatrix) + elem_size);
  assert(matrix != NULL);

  matrix->n = n;
  memset(matrix->elem, 0, elem_size);
  return matrix;
}

void trimatrix_free(Trimatrix* matrix)
{
  assert(matrix != NULL);

  free(matrix);  
}

int trimatrix_elem(Trimatrix* matrix, int i, int j)
{
  assert(matrix != NULL);
  assert((i >= 0) && (j >= 0));
  assert(j <= matrix->n);

  if (i > j) {
    int t = i;
    i = j;
    j = t;
  }

  return matrix->elem[j * (j+1) / 2 + i];
}

void trimatrix_set(Trimatrix* matrix, int i, int j, int value)
{
  assert(matrix != NULL);
  assert((i >= 0) && (j >= 0));
  assert(j <= matrix->n);
  
  if (i > j) {
    int t = i;
    i = j;
    j = t;
  }

  matrix->elem[j * (j+1) / 2 + i] = value;
}

